#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/16 9:32
# @Author  : JY.Liu
# @Site    : http://github.com/lh1993
# @Mail    : lhln0119@163.com
# @File    : redis_status_check.py
# @Software: PyCharm

import os
import sys
import json
from tools import k8s, my_redis, redis_manager

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_DIR = os.path.join(BASE_DIR, "config")
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")

with open(CONFIG_FILE, 'rb') as f:
    config = json.load(f)

redis_items = config['k8s'].items()
R = my_redis.Redis()


def redis_init():
    """redis POD IP信息存入redis，进行初始化

    :return:
    """

    for namespace, redis_item in redis_items:
        for key, pods_list in redis_item.items():
            # key: 应用名称
            # pods_list: pod名称列表
            redis_ip_list = []
            if not pods_list:
                pod_ip = k8s.get_namespaced_pod(
                    deployment_name=key, namespace=namespace, deployment=True)
                redis_ip_list.extend(pod_ip)
            else:
                for pod in pods_list:
                    pod_ip = k8s.get_namespaced_pod(
                        podname=pod, namespace=namespace)
                    redis_ip_list.extend(pod_ip)
            redis_ip = json.dumps(redis_ip_list)
            redis_name = "%s-%s" % (namespace, key)
            R.set(key=redis_name, value=redis_ip)


def redis_check():
    """检查redis POD IP是否更改

    :return:
    """
    for namespace, redis_item in redis_items:
        for key, pods_list in redis_item.items():
            print("#" * 25 + " " + key + " " + "#" * 25, flush=True)
            pod_ip_list = []
            if not pods_list:
                pod_ip = k8s.get_namespaced_pod(
                    deployment_name=key, namespace=namespace, deployment=True)
                pod_ip_list.extend(pod_ip)
            else:
                for pod in pods_list:
                    pod_ip = k8s.get_namespaced_pod(
                        podname=pod, namespace=namespace)
                    pod_ip_list.extend(pod_ip)
            redis_name = "%s-%s" % (namespace, key)
            redis_ip_list = json.loads(R.get(key=redis_name))
            print("redis中ip信息: %s" % redis_ip_list, flush=True)
            print("k8s中ip信息: %s" % pod_ip_list, flush=True)
            # 检查redis Pod的IP是否发生变化
            check_result = set(pod_ip_list) - set(redis_ip_list)
            print("redis容器IP是否变化：%s" % check_result, flush=True)
            if check_result:
                # 更新redis-manager中的redis地址信息
                RM = redis_manager.RedisManager()
                cluster_name = "%s-%s" % (namespace, key)
                node_list = []
                nodes = ""
                for pod_ip in pod_ip_list:
                    node_dict = {"value": "%s:6379" % pod_ip}
                    node_list.append(node_dict)
                    nodes += pod_ip + ":6379,"
                print("cluster_name: %s" % cluster_name, flush=True)
                print("node_list: %s" % node_list, flush=True)
                print("nodes: %s" % nodes, flush=True)
                RM.login()
                RM.update_cluster(cluster_name=cluster_name,
                                  node_list=node_list,
                                  nodes=nodes)
                # 重新将redis IP信息，保存到redis中
                print("redis POD IP信息存入redis，重新进行初始化", flush=True)
                redis_init()
            print("#" * 58, flush=True)


if __name__ == '__main__':
    args = sys.argv[-1]
    if args == "init":
        redis_init()
    else:
        redis_check()
